<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="系统自动生成"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalFlow">
              <j-dict-select-tag
                type="list"
                v-model="model.approvalFlow"
                dictCode="schedule_flow"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="调度开始" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beginDate">
              <j-date placeholder="请选择调度开始" v-model="model.beginDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="调度截止" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endDate">
              <j-date placeholder="请选择调度截止" v-model="model.endDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-row style="margin-top: 20px">
      <a-col :span="24">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslProScheduleDetailTable.loading"
          :columns="tslProScheduleDetailTable.columns"
          :dataSource="tslProScheduleDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="false"
          @cell-click="cellClickEvent"
        />
      </a-col>
    </a-row>
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <a-form-model-item label="包装要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageRemark">
              <a-textarea v-model="packageRemark" rows="4" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="质量要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualityRemark">
              <a-textarea v-model="qualityRemark" rows="4" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="特殊要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specialRemark">
              <a-textarea v-model="specialRemark" rows="4" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              :labelCol="{ xs: { span: 24 }, sm: { span: 1 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 22 } }"
              prop="remark"
            >
              <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { postAction } from '@/api/manage'

export default {
  name: 'TslProScheduleForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
  },
  data() {
    return {
      packageRemark: '',
      qualityRemark: '',
      specialRemark: '',
      salesType: '',
      productType: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        code: '',
        beginDate: '',
        endDate: '',
        remark: '',
        tslProScheduleDetailList: [],
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        approvalFlow: [{ required: true, message: '请输入审批流程!' }],
        beginDate: [{ required: true, message: '请选择调度开始日期', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择调度截止日期', trigger: 'change' }],
      },
      refKeys: ['productDetail', 'packageDetail', 'packageTable'],
      tableKeys: ['productDetail', 'packageDetail', 'packageTable'],
      activeKey: 'productDetail',
      // 生产调度令子表
      tslProScheduleDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '营销计划单号',
            key: 'planCode',
            type: JVXETypes.normal,
            width: 180,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            width: 180,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            width: 180,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'productCode',
            type: JVXETypes.normal,
            width: 180,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            width: 350,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            dataIndex: 'materialSpec',
            type: JVXETypes.normal,
            width: 100,
          },
          {
            title: '主单位',
            key: 'meUnit',
            dataIndex: 'meUnit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            width: 100,
            disabled: true,
          },
          {
            title: '主数量',
            key: 'mainQuantity',
            dataIndex: 'mainQuantity',
            width: 120,
          },
          {
            title: '辅单位',
            key: 'auUnit',
            dataIndex: 'auUnit',
            dictCode: 'zl_unit',
            type: JVXETypes.select,
            width: 100,
            disabled: true,
          },
          {
            title: '辅数量',
            key: 'auxiliaryQuantity',
            dataIndex: 'auxiliaryQuantity',
            width: 120,
          },
          {
            title: '计划数量',
            key: 'planQuantity',
            dataIndex: 'planQuantity',
            width: 120,
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            dataIndex: 'formulaNumber',
            width: 150,
            disabled: true,
          },
          {
            title: '配方名称',
            key: 'formulaName',
            dataIndex: 'formulaName',
            width: 200,
          },
        ],
      },
      url: {
        add: '/pro/tslProSchedule/add',
        edit: '/pro/tslProSchedule/edit',
        queryById: '/pro/tslProSchedule/queryById',
        queryOrderByCode: '/review/bussInternationalTradeOrders/queryByCode',
        waitGenerateList: '/pro/tslProSchedule/getGenerateByIds',
        tslProScheduleDetail: {
          list: '/pro/tslProSchedule/queryTslProScheduleDetailByMainId',
          listByPlanIds: '/pro/tslProSchedule/queryDetailByPlanIds',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    if (this.customFormData != null && this.customFormData.id) {
      this.edit(this.customFormData)
    }
  },
  methods: {
    cellClickEvent({ row }) {
      this.packageRemark = ''
      this.qualityRemark = ''
      this.specialRemark = ''
      if (row) {
        this.packageRemark = row.packReq
        this.qualityRemark = row.formulaReq
        this.specialRemark = row.specialRemark
      }
    },
    add(rows) {
      console.log(rows, '根据营销计划单新增')
      this.productType = rows.productType
      this.salesType = rows.salesType
      if (this.productType == 3) {
        this.tslProScheduleDetailTable.dataSource = rows.ids
      } else {
        postAction(this.url.waitGenerateList, { ids: rows.ids }).then((res) => {
          this.tslProScheduleDetailTable.dataSource = res.result
          if (res.result != null && res.result.length > 0) {
            this.cellClickEvent({ row: res.result[0] })
          }
        })
      }
    },
    addBefore() {
      this.tslProScheduleDetailTable.dataSource = []
    },
    /**
     * 编辑记录
     * @param {Object} record - 需要编辑的记录对象
     */
    edit(record) {
      this.model = record
      this.tslProScheduleDetailTable.dataSource = []
      getAction(this.url.tslProScheduleDetail.list, { id: record.id }).then((res) => {
        if (res.success) {
          this.tslProScheduleDetailTable.dataSource = res.result
          if (res.result != null && res.result.length > 0) {
            this.cellClickEvent({ row: res.result[0] })
          }
        }
      })
    },
    /**
     * 表单提交入口（供模态框调用）
     */
    async handleOk() {
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return
      //  调用接口提交（根据实际接口调整）
      this.confirmLoading = true
      this.model.tslProScheduleDetailList = this.tslProScheduleDetailTable.dataSource
      if (this.model.tslProScheduleDetailList != null && this.model.tslProScheduleDetailList.length > 0) {
        this.model.tslProScheduleDetailList.forEach((element) => {
          element.createBy = null
          element.createTime = null
        })
      }
      this.model.productType = this.productType
      this.model.salesType = this.salesType
      try {
        const url = this.model.code ? this.url.edit : this.url.add // 编辑/新增判断
        await postAction(url, this.model)
        this.$message.success('提交成功')
        this.$emit('ok') // 触发提交成功事件，通知模态框
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'))
      } finally {
        this.confirmLoading = false
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslProScheduleDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped></style>
